package com.zhiyizhen.handheld.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import androidx.annotation.NonNull;

import com.zhiyizhen.handheld.common.LogUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

public class NetStateInterceptor implements Interceptor {

    private final ConnectivityManager mConnectivityManager;

    public NetStateInterceptor(Context context) {
        mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    @Override
    @NonNull
    public Response intercept(@NonNull Chain chain) throws IOException {
        if (isConnected()) {
            return chain.proceed(chain.request());
        }
        throw new ResponseException("-1", "网络连接不可用");
    }

    public boolean isConnected() {
        if (mConnectivityManager == null) {
            LogUtil.e("ConnectivityManager is not initialized");
            return false;
        }

        try {
            NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (networkInfo == null) {
                LogUtil.d( "No active network found");
                return false;
            }
            return networkInfo.isAvailable();
        } catch (SecurityException e) {
            LogUtil.e("Missing ACCESS_NETWORK_STATE permission", e);
            return false;
        }

    }

}
